package com.kyxx.topics.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.DragAdapter;
import com.kyxx.topics.adapter.OtherAdapter;
import com.kyxx.topics.bean.TagBean;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.widget.DragGrid;
import com.kyxx.topics.widget.OtherGridView;
import com.loopj.android.http.RequestParams;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import okhttp3.Call;
import okhttp3.Response;

public class EditTagActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    GridView userGridView;
    GridView otherGridView;
    DragAdapter userAdapter;
    OtherAdapter otherAdapter;
    JSONArray jsonArray = new JSONArray();
    JSONArray jsonArrayNo = new JSONArray();
    private List<TagBean> tagBeanList = new ArrayList<>();
    private List<TagBean> tagBeanListNo = new ArrayList<>();
    /**
     * 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。
     */
    boolean isMove = false;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    tagBeanList = (List<TagBean>) msg.obj;

                    jsonArray = new JSONArray();
                    for (int i = 0; i < tagBeanList.size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("id", tagBeanList.get(i).getId());
                        jsonObject.put("title", tagBeanList.get(i).getTitle());
                        jsonArray.add(jsonObject);
                    }
                    String s = jsonArray.toString();
                    Log.e("tag", s);
                    break;
            }
        }
    };

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(title);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.VISIBLE);
        top_bar_tv_right.setText("保存");
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        top_bar_tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                HttpParams params = new HttpParams();
//                params.put("uid", BaseApp.getModel().getId());
//                params.put("tags", jsonArray.toString());
//                OkGoRequest.post(UrlUtils.UPTAGS, context, "uptags", CacheMode.REQUEST_FAILED_READ_CACHE, params, new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        finish();
//                    }
//                });

                RequestParams requestParams = new RequestParams();
                requestParams.put("uid", BaseApp.getModel().getId());
                requestParams.put("tags", jsonArray.toString());
                RestClient.post(UrlUtils.UPTAGS, requestParams, context, new ResponseListener(EditTagActivity.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, org.json.JSONObject result) {
                        Intent intent = new Intent();
                        intent.putExtra("tagBeanList", (Serializable) tagBeanList);
                        intent.putExtra("tagBeanListNo", (Serializable) tagBeanListNo);
                        setResult(47, intent);
                        finish();
                    }
                });
            }
        });
    }

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_edit_tag);
    }

    @Override
    protected void findViewById() {
        loadTopBar("频道管理");
        userGridView = (DragGrid) findViewById(R.id.userGridView);
        otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
    }

    @Override
    protected void setListener() {
        otherGridView.setOnItemClickListener(this);
        userGridView.setOnItemClickListener(this);
    }

    @Override
    protected void processLogic() {
        tagBeanList = (ArrayList<TagBean>) getIntent().getSerializableExtra("tagBeanList");
        tagBeanListNo = (ArrayList<TagBean>) getIntent().getSerializableExtra("tagBeanListNo");
        userAdapter = new DragAdapter(this, tagBeanList, handler);
        userGridView.setAdapter(userAdapter);
        otherAdapter = new OtherAdapter(this, tagBeanListNo);
        otherGridView.setAdapter(otherAdapter);
        for (int i = 0; i < tagBeanList.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", tagBeanList.get(i).getId());
            jsonObject.put("title", tagBeanList.get(i).getTitle());
            jsonArray.add(jsonObject);
        }
        for (int i = 0; i < tagBeanListNo.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id", tagBeanListNo.get(i).getId());
            jsonObject.put("title", tagBeanListNo.get(i).getTitle());
            jsonArrayNo.add(jsonObject);
        }
    }


    /**
     * GRIDVIEW对应的ITEM点击监听接口
     */
    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        //如果点击的时候，之前动画还没结束，那么就让点击事件无效
        if (isMove) {
            return;
        }
        switch (parent.getId()) {
            case R.id.userGridView:
                //position为 0，1 的不可以进行任何操作
//                if((tagBeanList.size()<3)&&(position==1)){
//                    ToastUtils.show(context,"请至少保留两个频道");
//                    return;
//                }
                if (position != 0) {
                    final ImageView moveImageView = getView(view);
                    if (moveImageView != null) {
                        TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                        final int[] startLocation = new int[2];
                        newTextView.getLocationInWindow(startLocation);
                        final TagBean channel = ((DragAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容
                        otherAdapter.setVisible(false);
                        //添加到最后一个
                        otherAdapter.addItem(channel);
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                try {
                                    int[] endLocation = new int[2];
                                    //获取终点的坐标
                                    otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                    MoveAnim(moveImageView, startLocation, endLocation, channel, userGridView);
                                    userAdapter.setRemove(position);
                                } catch (Exception localException) {
                                }
                            }
                        }, 50L);
                    }
                }
                break;
            case R.id.otherGridView:
                final ImageView moveImageView = getView(view);
                if (moveImageView != null) {
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);
                    final TagBean channel = ((OtherAdapter) parent.getAdapter()).getItem(position);
                    userAdapter.setVisible(false);
                    //添加到最后一个
                    userAdapter.addItem(channel);
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                MoveAnim(moveImageView, startLocation, endLocation, channel, otherGridView);
                                otherAdapter.setRemove(position);
                            } catch (Exception localException) {
                            }
                        }
                    }, 50L);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 点击ITEM移动动画
     *
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final TagBean moveChannel,
                          final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    otherAdapter.setVisible(true);
                    otherAdapter.notifyDataSetChanged();
                    userAdapter.remove();
                } else {
                    userAdapter.setVisible(true);
                    userAdapter.notifyDataSetChanged();
                    otherAdapter.remove();
                }
                isMove = false;
            }
        });
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(this);
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取点击的Item的对应View，
     *
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(cache);
        return iv;
    }
}
